<template>
  <div class="project-list">
    <el-table
      :data="projects"
      style="width: 100%"
      border
      :row-class-name="tableRowClassName"
      @row-click="handleRowClick"
      empty-text=""
    >
      <el-table-column label="选择" width="80" align="center">
        <template #default="{ row }">
          <el-radio v-model="localSelectedProjectId" :label="row.id" @change="handleSelectProject(row.id)"></el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="项目名称" align="center"></el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElRadio, ElTable, ElTableColumn } from 'element-plus';
import 'element-plus/dist/index.css';

// 定义组件属性
const props = defineProps({
  // 项目列表数据
  projects: {
    type: Array,
    default: () => [
      { id: 1, name: '项目一' },
      { id: 2, name: '项目二' }
    ]
  },
  // 当前选中的项目ID
  selectedProjectId: {
    type: [Number, String],
    default: 1
  }
});

// 定义组件事件
const emit = defineEmits(['project-change']);

// 本地选中的项目ID，用于v-model绑定
const localSelectedProjectId = ref(props.selectedProjectId);

// 监听外部selectedProjectId变化，同步到本地
watch(
  () => props.selectedProjectId,
  newValue => {
    localSelectedProjectId.value = newValue;
  }
);

// 处理项目选择
const handleSelectProject = projectId => {
  // 更新本地选中状态
  localSelectedProjectId.value = projectId;
  // 触发项目变更事件
  emit('project-change', projectId);
};

// 处理行点击事件
const handleRowClick = row => {
  handleSelectProject(row.id);
};

// 表格行样式类名
const tableRowClassName = ({ row }) => {
  // 确认是否正确计算了选中状态
  return row.id === props.selectedProjectId ? 'active-row' : '';
};
</script>

<style scoped>
.project-list {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

.el-table {
  width: 100%;
}

/* 为选中行添加左侧标记线 - 作为选中的主要视觉提示 */
.el-table :deep(tr.active-row > td:first-child) {
  border-left: 3px solid #1890ff;
}

:deep(.el-table tr) {
  background-color: transparent;
}

:deep(.el-table th.el-table__cell) {
  background-color: rgba(0, 0, 0, 0.1);
}
</style>
